package com.travel.travel_springboot_web.controller;

import com.travel.travel_springboot_web.entity.Address;
import com.travel.travel_springboot_web.service.AddressService;
import com.travel.travel_springboot_web.utils.JwtUtil;
import com.travel.travel_springboot_web.utils.TokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/address")
@CrossOrigin(
    originPatterns = {"http://localhost:*", "http://127.0.0.1:*"},
    methods = {
        RequestMethod.GET, 
        RequestMethod.POST, 
        RequestMethod.PUT, 
        RequestMethod.DELETE, 
        RequestMethod.OPTIONS
    },
    allowCredentials = "true"
)
public class AddressController {
    
    private static final Logger logger = LoggerFactory.getLogger(AddressController.class);
    
    @Autowired
    private AddressService addressService;
    
    @Autowired
    private TokenUtil tokenUtil;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @PostMapping
    public Map<String, Object> create(
            @RequestBody Address address,
            @RequestHeader(value = "Authorization", required = false) String authHeader) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 提取并验证token
            String token = tokenUtil.extractToken(authHeader);
            if (!jwtUtil.validateToken(token)) {
                throw new RuntimeException("无效的登录令牌");
            }
            
            // 从token中获取用户ID
            Long userId = jwtUtil.getUserIdFromToken(token);
            logger.info("Creating address for user: {}", userId);
            
            if (userId == null) {
                throw new RuntimeException("请先登录");
            }
            
            // 设置当前用户ID
            address.setUserId(userId);
            
            Address savedAddress = addressService.createAddress(address);
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", savedAddress);
        } catch (Exception e) {
            logger.error("Failed to create address: ", e);
            result.put("code", e.getMessage().contains("请先登录") ? 401 : 500);
            result.put("message", e.getMessage());
        }
        return result;
    }
    
    @GetMapping("/list")
    public Map<String, Object> list(
            @RequestHeader(value = "Authorization", required = false) String authHeader) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 提取并验证token
            String token = tokenUtil.extractToken(authHeader);
            
            // 从token中获取用户ID
            Long userId = jwtUtil.getUserIdFromToken(token);
            logger.info("Getting address list for user: {}", userId);
            
            if (userId == null) {
                throw new RuntimeException("请先登录");
            }
            
            List<Address> addresses = addressService.getAddressList(userId);
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", addresses);
        } catch (Exception e) {
            logger.error("Failed to get address list: ", e);
            result.put("code", e.getMessage().contains("请先登录") ? 401 : 500);
            result.put("message", e.getMessage());
        }
        return result;
    }
    
    @PutMapping("/{id}")
    public Map<String, Object> update(
            @PathVariable Long id, 
            @RequestBody Address address,
            @RequestHeader(value = "Authorization", required = false) String authHeader) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 提取并验证token
            String token = tokenUtil.extractToken(authHeader);
            if (!jwtUtil.validateToken(token)) {
                throw new RuntimeException("无效的登录令牌");
            }
            
            // 从token中获取用户ID
            Long userId = jwtUtil.getUserIdFromToken(token);
            logger.info("Updating address: {} for user: {}", id, userId);
            
            if (userId == null) {
                throw new RuntimeException("请先登录");
            }
            
            address.setUserId(userId);
            address.setId(id);
            
            boolean success = addressService.updateAddress(address);
            if (success) {
                result.put("code", 200);
                result.put("message", "success");
            } else {
                result.put("code", 404);
                result.put("message", "地址不存在");
            }
        } catch (Exception e) {
            logger.error("Failed to update address: ", e);
            result.put("code", e.getMessage().contains("请先登录") ? 401 : 500);
            result.put("message", e.getMessage());
        }
        return result;
    }
    
    @DeleteMapping("/{id}")
    public Map<String, Object> delete(
            @PathVariable Long id,
            @RequestHeader(value = "Authorization", required = false) String authHeader) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 提取并验证token
            String token = tokenUtil.extractToken(authHeader);
            if (!jwtUtil.validateToken(token)) {
                throw new RuntimeException("无效的登录令牌");
            }
            
            // 从token中获取用户ID
            Long userId = jwtUtil.getUserIdFromToken(token);
            logger.info("Deleting address: {} for user: {}", id, userId);
            
            if (userId == null) {
                throw new RuntimeException("请先登录");
            }
            
            boolean success = addressService.deleteAddress(id, userId);
            if (success) {
                result.put("code", 200);
                result.put("message", "success");
            } else {
                result.put("code", 404);
                result.put("message", "地址不存在");
            }
        } catch (Exception e) {
            logger.error("Failed to delete address: ", e);
            result.put("code", e.getMessage().contains("请先登录") ? 401 : 500);
            result.put("message", e.getMessage());
        }
        return result;
    }
} 